﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.IO;
using Terraria;
using Terraria.GameContent;
using Terraria.GameContent.Creative;
using Terraria.ID;
using Terraria.ModLoader;
using Terraria.ModLoader.IO;

namespace Bundlesone.Content.Items
{
    public class Bundle : ModItem
    {
        public Item[] StoredItems = new Item[12];

        public override void SetStaticDefaults()
        {
            CreativeItemSacrificesCatalog.Instance.SacrificeCountNeededByItemId[Type] = 15;
        }
        public override bool PreDrawInInventory(SpriteBatch spriteBatch, Vector2 position, Rectangle frame, Color drawColor, Color itemColor, Vector2 origin, float scale)
        {
            Texture2D texture = IsFull() ? ModContent.Request<Texture2D>("Bundlesone/Content/Items/Bundle_Full").Value : TextureAssets.Item[Type].Value;
            spriteBatch.Draw(texture, position, frame, drawColor, 0f, origin, scale, SpriteEffects.None, 0f);
            return false;
        }
        public bool IsFull()
        {
            for (int i = 0; i < StoredItems.Length; i++)
            {
                if (StoredItems[i].IsAir)
                    return false;
            }
            return true;
        }
        public override void SetDefaults()
        {
            StoredItems = new Item[12];
            for (int i = 0; i < StoredItems.Length; i++)
            {
                StoredItems[i] = new Item();
                StoredItems[i].TurnToAir();
            }
            Item.width = 24;
            Item.height = 24;
            Item.maxStack = 1;
            Item.rare = ItemRarityID.Blue;
            Item.value = Item.sellPrice(0, 1, 0, 0);
            Item.useStyle = ItemUseStyleID.HoldUp;
            Item.useTime = 20;
            Item.useAnimation = 20;
            Item.noMelee = true;
        }

        public override bool? UseItem(Player player)
        {
            var uiSystem = ModContent.GetInstance<BundleUISystem>();
            if (!uiSystem.IsUIOpen)
            {
                uiSystem.ToggleBundleUI(this);
            }
            return true;
        }
        public override void AddRecipes()
        {
            CreateRecipe()
                .AddIngredient(ItemID.Silk, 3)
                .AddIngredient(ItemID.Rope, 1)
                .AddTile(TileID.WorkBenches)
                .Register();
        }

        public override void SaveData(TagCompound tag)
        {
            for (int i = 0; i < StoredItems.Length; i++)
            {
                if (StoredItems[i] == null)
                {
                    StoredItems[i] = new Item();
                    StoredItems[i].TurnToAir();
                }
                tag.Add($"StoredItem_{i}", ItemIO.Save(StoredItems[i]));
            }
        }

        public override void LoadData(TagCompound tag)
        {
            for (int i = 0; i < StoredItems.Length; i++)
            {
                string key = $"StoredItem_{i}";
                if (StoredItems[i] == null)
                    StoredItems[i] = new Item();
                if (tag.ContainsKey(key))
                {
                    StoredItems[i] = ItemIO.Load(tag.GetCompound(key));
                }
                else
                {
                    StoredItems[i].TurnToAir();
                }
            }
        }

        public override void NetSend(BinaryWriter writer)
        {
            for (int i = 0; i < StoredItems.Length; i++)
            {
                if (StoredItems[i] == null)
                {
                    StoredItems[i] = new Item();
                    StoredItems[i].TurnToAir();
                }
                ItemIO.Send(StoredItems[i], writer, writeStack: true);
            }
        }

        public override void NetReceive(BinaryReader reader)
        {
            for (int i = 0; i < StoredItems.Length; i++)
            {
                StoredItems[i] = ItemIO.Receive(reader, readStack: true);
            }
        }
        public float GetFillPercentage()
        {
            int filledSlots = 0;
            for (int i = 0; i < StoredItems.Length; i++)
            {
                if (StoredItems[i] != null && !StoredItems[i].IsAir)
                    filledSlots++;
            }
            return (float)filledSlots / StoredItems.Length;
        }
        public override void PostDrawInInventory(SpriteBatch spriteBatch, Vector2 position, Rectangle frame, Color drawColor, Color itemColor, Vector2 origin, float scale)
        {
            float fillPercent = GetFillPercentage();
            int barHeight = 4;
            int barWidth = (int)(frame.Width * scale * 0.9f);
            int yOffset = -8;
            Vector2 barPosition = position + new Vector2((frame.Width * scale - barWidth) / 2 - 12, frame.Height * scale - barHeight + yOffset);
            Rectangle barRect = new((int)barPosition.X, (int)barPosition.Y, barWidth, barHeight);
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, barRect, Color.Black * 0.7f);
            int fillWidth = (int)(barWidth * fillPercent);
            if (fillWidth > 0)
            {
                Rectangle fillRect = new((int)barPosition.X, (int)barPosition.Y, fillWidth, barHeight);
                Color fillColor = Color.Lerp(Color.Lime, Color.Red, fillPercent) * 0.9f;
                spriteBatch.Draw(TextureAssets.MagicPixel.Value, fillRect, fillColor);
            }
        }
    }
}